<?php

class stabImportCsvAllTask extends sfPropelBaseTask
{
  protected function configure()
  {
    $this->namespace        = 'stab';
    $this->name             = 'import-csv-all';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [stab:import-csv-all|INFO] task does things.
Call it with:

  [php symfony stab:import-csv-all|INFO]
EOF;
    $this->addArgument('application', sfCommandArgument::REQUIRED, 'The application name');
    // add other arguments here
    $this->addOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev');
    $this->addOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'propel');
    // add other options here
  }

  protected function execute($arguments = array(), $options = array())
  {
    // Database initialization
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = Propel::getConnection($options['connection'] ? $options['connection'] : '');
    // add code here

    $update = false;
    if(in_array("update", $args))
    {
        $update = true;
    }
    
    if(is_dir(sfConfig::get('sf_data_dir').DIRECTORY_SEPARATOR.'tournament'))
    {
        // Get all folders in the tournament directory
        foreach(scandir(sfConfig::get('sf_data_dir').DIRECTORY_SEPARATOR.'tournament') as $institutionFolder)
        {
            // Filter out anything that starts with a .
            if(is_dir(sfConfig::get('sf_data_dir').DIRECTORY_SEPARATOR.'tournament'.DIRECTORY_SEPARATOR.$institutionFolder) 
              and substr($institutionFolder, 0, 1) != '.')
            {
                echo "Importing from folder: " . sfConfig::get('sf_data_dir') . 
                DIRECTORY_SEPARATOR . 'tournament' . DIRECTORY_SEPARATOR . 
                $institutionFolder . "\n";
                foreach(array('Institution', 'Team', 'Debater', 'Adjudicator') as $model)
                {
                    if(is_file(sfConfig::get('sf_data_dir').DIRECTORY_SEPARATOR.'tournament'.DIRECTORY_SEPARATOR.$institutionFolder.DIRECTORY_SEPARATOR.sfInflector::underscore($model) . '.csv'))
                    {
                        echo "Importing $model from file: " . sfConfig::get('sf_data_dir') . 
                        DIRECTORY_SEPARATOR.'tournament'.DIRECTORY_SEPARATOR.
                        $institutionFolder.DIRECTORY_SEPARATOR.sfInflector::underscore($model) . ".csv\n";
                        
                        import_csv_file($model, $institutionFolder, $update);
                    }
                }
            }
        }
    }

  }
}
